<template>
  <div>
    <div class="flex flex-column open-box justify-between">
      <div class="flex p-10">
        <label>{{ $t('SERVICE_NAME') }}：</label>
        <p class="flex-1">{{ bizData.bizName }}</p>
      </div>
      <!-- 选中端口信息 -->
      <BaseInfo :form-data="formData" />
      <!-- 链路选择 -->
      <div class="route-list-info flex-1 p-5 flex overflow-auto" style="flex-direction: column">
        <div v-if="channelList.length" class="mt-5 mb-5">{{ $t('LINK') }}：</div>
        <div
          v-for="(item, index) in channelList"
          :key="index"
          class="flex justify-start mb-10 mt-10 top-open-link"
          style="flex-direction: column"
          @click="showRouteDetail(item)"
        >
          <label>{{ $t('CHANNEL') + (index + 1) }}：<label />
            <div class="w-100 pr-10">
              <p>
                {{ $t('NODE_NUM') }}：{{ item.nodeNum }}； {{ $t('FIBER_TOTAL_TIME') }}：{{
                  item.cutoverTime > 990000 || 0 > item.cutoverTime ? '--' : item.cutoverTime
                }}； {{ $t('LINK_LOSS') }}：{{
                  item.loss > 990000 ? '--' : changeDecimal(item.loss, 3)
                }}； {{ $t('LESS_LENGTH') }}：{{ item.linkLength }}
              </p>
              <el-link
                type="primary"
                :underline="false"
                class="white-space-normal"
                @mouseenter.native="mouseEvent(item, 'always')"
                @mouseleave.native="mouseEvent(item, 'leave')"
              >
                {{ $t('INTERMEDIATE_NODE') }}：
                {{ item.linkInfo }}
              </el-link>
            </div>
            <p class="font-small">{{ $t('MOVE_FIBER_DESCRIPTION') }}：
              <span v-html="cutoverDesc(item)" />
            </p>
          </label>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div class="p-5 pt-0 pb-0">
        <div>
          <!-- 还原时间选择 -->
          <el-form ref="timeForm" :model="form" label-width="110px" :rules="rules">
            <el-form-item :label="$t('REDUCTION_START_TIME')" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                popper-class="reduction-time-picker"
                :disabled="disableTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                data-format="yyyy-MM-dd HH:mm"
                :picker-options="startPickerOptions"
                style="width: 200px"
                :placeholder="$t('REDUCTION_START_TIME')"
                :clearable="false"
                :default-value="new Date()"
                :default-time="formatDate(new Date(), 'HH:mm:ss')"
              />
              <!-- <el-popover width="200" trigger="hover">
                <div class="text-color" v-html="$t('REDUCTION_START_TIME_TIPS')" />
                <i slot="reference" class="iconfont icon-AFSwenhao ml-5" />
              </el-popover> -->
            </el-form-item>
          </el-form>
        </div>
        <div class="flex justify-end">
          <el-button v-if="disableTime" @click="del">{{ $t('CANCEL_REDUCTION') }}</el-button>
          <el-button @click="close">{{ $t('CLOSE') }}</el-button>
          <el-button v-if="!disableTime" type="primary" @click="save">{{ $t('SAVE') }}</el-button>
        </div>
      </div>
      <!-- 通道列表 -->
      <el-dialog
        v-el-drag-dialog="{updataFull, updataDialogWidth}"
        :fullscreen="isfullscreen"
        :title="$t('INTERMEDIATE_NODE')"
        :visible.sync="routeDetailShow"
        :modal="false"
        :width="setDialogWidth('1000px')"
      >
        <div class="text-color text-center">{{ $t('CURRENT_LINK_CHANNEL') }}</div>
        <biz-graphical
          ref="curBizGraphical"
          class="mb-20"
          :biz-channel-list="useSegmentList"
          :cable-data="graphicalCableData"
        />
        <div class="text-color text-center">{{ $t('RESTORE_TO_ORIGINAL') }}</div>
        <biz-graphical
          ref="targetBizGraphical"
          class="mb-20"
          :biz-channel-list="targetSegmentList"
          :cable-data="graphicalCableData"
          operate-type="reduction"
        />
        <span slot="footer">
          <el-button type="primary" @click="routeDetailShow = false">{{ $t('CLOSE') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { mapGetters, mapMutations } from 'vuex'
  import {
    deepClone,
    checkAfs,
    changeDecimal,
    formatDate,
    correctOrder,
    getDateTime
  } from '@/utils/common'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import BaseInfo from './BaseInfo'
  import BizGraphical from '@/components/BizGraphical'

  export default {
    components: {
      BaseInfo,
      BizGraphical
    },
    props: {
      bizData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['functionName', 'parentVM'],
    data() {
      return {
        changeDecimal: changeDecimal,
        form: {
          startTime: ''
        },
        formData: {
          aPortData: null,
          zPortData: null,
          segmentList: [],
          routeData: null,
          channelData: []
        },
        formatDate: formatDate,
        startPickerOptions: {
          disabledDate: time => {
            return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000
          }
        },
        disableTime: false,
        channelList: [],
        routeList: [],
        routeDetailShow: false,
        useSegmentList: [],
        targetSegmentList: [],
        graphicalCableData: {}
      }
    },
    computed: {
      ...mapGetters(['baseRegionList']),
      rules() {
        return {
          startTime: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('REDUCTION_START_TIME'),
              trigger: ['blur', 'change']
            },
            { validator: this.checkeTime, trigger: ['blur', 'change'] }
          ]
        }
      }
    },
    watch: {
      'bizData.bizId': function() {
        this.init()
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      ...mapMutations(['setGisActived']),
      init() {
        this.disableTime = false
        this.formData = this.$options.data().formData
        this.getDetail()
        this.formatBizData()
        this.getReductionInfo()
      },
      // 检测时间必须大于当前时间
      checkeTime(rule, value, callback) {
        const ok =
          this.form.startTime && new Date(this.form.startTime).getTime() < new Date().getTime()
        ok ? callback(new Error(this.$t('RESTORE_TIME_ERROR'))) : callback()
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      },
      // 拼接业务基本信息
      formatBizData() {
        console.log('this.bizData', this.bizData)
        const channelData = this.bizData.channelList[0]
        const startData = channelData.segmentList[0]
        this.formData.bizId = this.bizData.bizId
        this.formData.aPortData = {
          nodeType: startData.startNode.nodeCategory,
          nodeId: startData.startNodeId,
          nodeName: startData.startNode.nodeName,
          regionId: startData.startNode.stationId,
          regionName: this.getRegionName(startData.startNode.stationId),
          portId: startData.startPortId,
          portName: startData.startPort.bizName,
          interfaceType: 'SINGLE',
          funcType: 'SEND_RECEIVE'
        }
        const endData = channelData.segmentList[channelData.segmentList.length - 1]
        this.formData.zPortData = {
          nodeType: endData.endNode.nodeCategory,
          nodeId: endData.endNodeId,
          nodeName: endData.endNode.nodeName,
          regionId: endData.endNode.stationId,
          regionName: this.getRegionName(endData.endNode.stationId),
          portId: endData.endPortId,
          portName: endData.endPort.bizName,
          interfaceType: 'SINGLE',
          funcType: 'SEND_RECEIVE'
        }
        if (this.bizData.channelList[1]) {
          const channelData2 = this.bizData.channelList[1]
          const startData = channelData2.segmentList[0]
          this.formData.aPortData2 = {
            nodeType: startData.startNode.nodeCategory,
            nodeId: startData.startNodeId,
            nodeName: startData.startNode.nodeName,
            regionId: startData.startNode.stationId,
            regionName: this.getRegionName(startData.startNode.stationId),
            portId: startData.startPortId,
            portName: startData.startPort.bizName,
            interfaceType: 'SINGLE',
            funcType: 'SEND_RECEIVE'
          }
          const endData = channelData2.segmentList[channelData2.segmentList.length - 1]
          this.formData.zPortData2 = {
            nodeType: endData.endNode.nodeCategory,
            nodeId: endData.endNodeId,
            nodeName: endData.endNode.nodeName,
            regionId: endData.endNode.stationId,
            regionName: this.getRegionName(endData.endNode.stationId),
            portId: endData.endPortId,
            portName: endData.endPort.bizName,
            interfaceType: 'SINGLE',
            funcType: 'SEND_RECEIVE'
          }
        }
        console.log('this.formData', this.formData)
      },
      // 获取备用详情
      getDetail() {
        this.channelList = []
        bizOpenApi.initialChannel({ bizId: this.bizData.bizId }).then(res => {
          const useSegmentList = []
          const targetSegmentList = []
          res.forEach(i => {
            // 获取光缆信息
            const nodeList = {}
            i.targetNetworkSegmentList.forEach(j => {
              nodeList[j.startNodeId] = j.startNode
              nodeList[j.endNodeId] = j.endNode
              if (j.cable) {
                this.graphicalCableData[j.cableId] = j.cable
              }
            })
            i.useNetworkSegmentList.forEach(j => {
              nodeList[j.startNodeId] = j.startNode
              nodeList[j.endNodeId] = j.endNode
              if (j.cable) {
                this.graphicalCableData[j.cableId] = j.cable
              }
            })
            i.targetSegmentChannelList = correctOrder(
              i.targetSegmentChannelList,
              this.bizData.startNodeId
            )
            i.linkLength = changeDecimal(i.linkLength, 3, true)
            const linkInfo = []
            const endNodeList = []

            i.targetSegmentChannelList.forEach((j, index) => {
              j.startNode = j.startNode || nodeList[j.startNodeId] || {}
              j.endNode = j.endNode || nodeList[j.endNodeId] || {}
              if (index === 0) {
                linkInfo.push(j.startNode.nodeName)
              }
              linkInfo.push(j.endNode.nodeName)
              endNodeList.push(j.endNodeId)
            })
            i.cutoverList.sort((a, b) => {
              const aIndex = endNodeList.indexOf(a.deviceId)
              const bIndex = endNodeList.indexOf(b.deviceId)
              return aIndex - bIndex
            })
            i.linkInfo = linkInfo.join('-->')
            useSegmentList.push({ segmentList: i.useSegmentChannelList })
            targetSegmentList.push({ segmentList: i.targetSegmentChannelList })
          })
          this.channelList = res || []
          this.useSegmentList = useSegmentList
          this.targetSegmentList = targetSegmentList
        })
      },
      // 拼装组合通道展示数据
      formatData(data) {
        // 拼接组合数据：同链路数据拼接到一条里面
        const newList = []
        data.forEach(i => {
          // 设置链路唯一linkId 使用通道id拼接保证一定是唯一的
          i.linkId = i.segmentList.map(j => j.id).join()
          i.checked = false
          const theIndex = newList.findIndex(j => j.linkId === i.linkId)
          const item = deepClone(i)
          const channelItem = {
            segmentListIds: i.linkId,
            loss: i.loss,
            backId: i.backId,
            exclusive: i.exclusive ? 'EXCLUSIVE' : 'SHARE',
            segmentList: i.channelList
          }
          if (theIndex !== -1) {
            newList[theIndex].channelList.push(channelItem)
          } else {
            item.channelList = [channelItem]
            newList.push(item)
          }
        })
        // 同链路通道拼接完成，设置表单显示信息
        newList.forEach(z => {
          z.channelList.forEach(i => {
            i.segmentList.forEach((j, index) => {
              j.startPort.bizName = this.$utils.handleServiceI18n(j.startPort.bizName)
              j.endPort.bizName = this.$utils.handleServiceI18n(j.endPort.bizName)
              i['segmentList' + index] = j
            })
          })
        })
        return newList
      },
      showRouteDetail(data) {
        this.routeDetailShow = true
        this.$nextTick(() => {
          this.$refs.curBizGraphical && this.$refs.curBizGraphical.formatData()
          this.$refs.targetBizGraphical && this.$refs.targetBizGraphical.formatData()
        })
      },
      cutoverDesc(row) {
        const desc = []
        row.cutoverList.forEach((i, index2) => {
          const str = this.$t('PORT_CONNECT_LINK', {
            msg1: i.deviceName,
            msg2: i.port.bizName,
            msg3: i.connPort.bizName
          })
          desc.push(str)
        })
        return desc.join('；') || this.$t('NO_PIPETTING_IS_REQUIRED')
      },
      getReductionInfo() {
        bizOpenApi.reductionInfo({ bizId: this.bizData.bizId }).then(res => {
          if (!res) return
          this.disableTime = new Date(res.executeTime).getTime() > new Date().getTime()
          this.form = {
            startTime: res.executeTime
          }
        })
      },
      mouseEvent(data, type) {
        // 还原至目标链路的光缆和站点高亮
        if (data.targetNetworkSegmentList && data.targetNetworkSegmentList.length) {
          const nodeIds = []
          const cableIds = data.targetNetworkSegmentList
            .filter(i => {
              nodeIds.push(i.startNode.stationId, i.endNode.stationId)
              return i.cableId
            })
            .map(i => i.cableId)
          if (type === 'always') {
            this.setGisActived({
              cableIds: Array.from(new Set(cableIds)),
              nodeIds: Array.from(new Set(nodeIds)),
              color: 'color-normal'
            })
          } else {
            this.setGisActived({
              cableIds: [],
              nodeIds: [],
              color: ''
            })
          }
        }
      },
      // 删除还原信息
      del() {
        this.$confirm(this.$t('CONFIRM_DELETE_REDUCTION'), { type: 'warning' })
          .then(() => {
            bizOpenApi.delReduction({
              bizId: this.bizData.bizId,
              functionName: this.parentVM.functionName || this.functionName, // 操作日志需要的参数
              bizName: this.bizData.bizName // 操作日志需要的参数
            })
              .then(res => {
                this.$message.success(this.$t('REQUEST_SUCCESS'))
                this.form = {
                  startTime: ''
                }
                this.disableTime = false
              })
          })
          .catch(() => {})
      },
      close(data) {
        this.$emit('close', data)
        this.form = this.$options.data().form
        this.$nextTick(() => {
          this.$refs.timeForm && this.$refs.timeForm.clearValidate()
        })
      },
      save() {
        this.$refs.timeForm.validate(valid => {
          if (!valid) return
          this.$confirm(this.$t('CONFIRM_START_RESTORE'), { type: 'warning' })
            .then(() => {
              this.submit()
            })
            .catch(() => {})
        })
      },
      async submit() {
        // 判断原通道AFS设备是否可用
        // const checkeAfs = await checkAfs(
        //   {
        //     routeData: {
        //       segmentList: this.channelList[0].targetNetworkSegmentList
        //     },
        //     channelData: this.channelList
        //   },
        //   'INTELLIGENCE_RESTORE'
        // )
        // if (!checkeAfs) return
        bizOpenApi.reductionChannelIdle({ bizId: this.bizData.bizId }).then(res => {
          if (!res) {
            this.$message.error(this.$t('ORIGINAL_LINK_CANNOT_RESTORED'))
            return
          }
          const queryData = {
            bizName: this.bizData.bizName,
            bizId: this.bizData.bizId,
            executeTime: getDateTime(this.form.startTime),
            functionName: this.parentVM.functionName || this.functionName
          }
          bizOpenApi.reduction(queryData).then(res => {
            this.$message.success(this.$t('REQUEST_SUCCESS'))
            this.close(true)
          })
        })
      }
    }
  }
</script>

<style lang="scss">
  .reduction-time-picker {
    .el-scrollbar:nth-child(3) {
      display: none !important;
    }
    .el-time-spinner {
      text-align: center;
    }
  }
</style>
